<?php

namespace App\service\order;

use Exception;
use support\Log;
use AdaPay\AdaPay;
use support\Redis;
use think\facade\Db;
use PhpAmqpLib\Wire\AMQPTable;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use crmeb\exceptions\AdminException;
use think\db\exception\{DataNotFoundException, DbException, ModelNotFoundException};

include_once app_path() . '/../' . 'extend/AdapaySdk/init.php';
include_once app_path() . '/../' . 'extend/checkstand/class/H5Cashier.php';

class RefundOrderServices
{
    public function __construct()
    {
        AdaPay::init(app_path() . '/../' . '/extend/AdapayDemo/config/config.json', "live", false);
    }

    /**
     * 退款申请
     * @param string $oriOrderCode
     * @return array|bool|string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function orderRefund(string $oriOrderCode)
    {
        $orderInfo = Db::name('store_order')->where('order_id', $oriOrderCode)->find();

        if (!$orderInfo) {
            return true; // 订单不存在
        }
        if ($orderInfo['refund_order_id']) {
            return true; // 此笔订单已经退款过
        }
        $orderId = 'Y' . $this->orderId(); // 新单号
        $client = new \H5Cashier;
        // 参数
        $totalAmount = intval($orderInfo['pay_price'] * 100);
        $var = sprintf("%012d", $totalAmount);
        $client->body = array(
            'orderCode' => $orderId, //新的订单号 指发起交易的流水号，建议订单号有日期
            'oriOrderCode' => $oriOrderCode, //原订单号   待退款的商户订单号
            'refundAmount' => $var, //退款金额  例 000000000101 代表 1.01 元
//            'refundMarketAmount' => '000000000012', //退营销金额
            'notifyUrl' => env('PAY_NOTIFY_URL') . '/orderApi/payNotify',
            'refundReason' => '订单超时退款', // 描述退款申请原因
            'extend' => '' // 扩展域
        );

        // 返回结果
        $ret = $client->request('orderRefund');
        if (!empty($ret['data'])) {
            $ret['data'] = json_decode($ret['data'], true);

            if ($ret['data']['head']['respCode'] == "000000") {
                // 订单状态（0 支付中 1 已付款未到账   2 已付款已到账 3 已退款 4 订单超时 5 支付失败（或者待支付））
                Db::name('store_order')->where('id', $orderInfo['id'])->update([
                    'status' => 3,
                    'refund_order_id' => $orderId,
                    'refund_reason_time' => date('Y-m-d H:i:s')
                ]);
            }
        }
        return $ret;
    }

    /**
     * @return string
     */
    public function orderId()
    {
        return date('Ymd') . substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }
}
